﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using suirui.ZhuMu.Common;

namespace suirui.ZhuMu.Framework
{
    public class TokenValidate
    {
        public static readonly List<Userrefreshtoken> _userRefreshTokens = new List<Userrefreshtoken>();

        /// <summary>
        /// 验证刷新token是否存在或过期
        /// </summary>
        /// <param name="refreshToken"></param>
        /// <returns></returns>
        public static bool IsValidRefreshToken(string refreshToken)
        {
            return _userRefreshTokens.Any(d => d.Token.Equals(refreshToken) && d.Active);
        }

        /// <summary>
        /// 创建刷新Token
        /// </summary>
        /// <param name="token"></param>
        /// <param name="userId"></param>
        public static void CreateRefreshToken(string token, string userId)
        {
            var refreshExpiredTime = AppConfigration.Configuration["refreshTokenExpiredDays"];
            var days = string.IsNullOrWhiteSpace(refreshExpiredTime) ? 7 : Convert.ToDouble(refreshExpiredTime);

            _userRefreshTokens.Add(new Userrefreshtoken() { Token = token, UserId = userId, Expires = DateTime.Now.AddDays(days) });
        }

        /// <summary>
        /// 移除刷新token
        /// </summary>
        /// <param name="refreshToken"></param>
        public static void RemoveRefreshToken(string refreshToken)
        {
            _userRefreshTokens.Remove(_userRefreshTokens.FirstOrDefault(t => t.Token == refreshToken));
        }

        /// <summary>
        /// 清空刷新Token列表
        /// </summary>
        public static void ClearAllRefreshTokenList()
        {
            _userRefreshTokens.Clear();
        }
    }
}
